/**
 * Created by tanbingqin on 2019/7/17.
 */
import { messages } from "share/common";
import React from 'react'
import constants from 'share/constants'
import { connect } from 'react-redux'
import moment from 'moment'
import errorMessage from 'share/errorMessage';
import Chooser from 'components/chooser'
import { Popover, Table, Affix, message, Button, Alert, Row, Col, Badge, Modal } from 'antd'
import ResizeTable from "components/resize-table";
import ApproveBar from 'components/template/approve-bar'
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'

import 'styles/approve/request/request.scss'
import 'styles/setting/process-monitoring-platform/process-monitoring-platform.scss'
import checkingImg from 'images/checking.png'
import loadingImg from 'images/loading.png'


class BatchTransferList extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      page: 0,
      pageSize: 10,
      columns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) =>
          (index + 1 + this.state.pageSize * this.state.page)
        },
        {
          title: messages('setting.key873'/*工号*/), dataIndex: 'employeeID', width: '6%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key855'/*申请人*/),
          dataIndex: 'applicantName',
          width: '8%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key874'/*提交日期*/),
          dataIndex: 'submittedDate',
          sorter: true,
          width: 120,
          render: value => moment(value).format('YYYY-MM-DD')
        },
        {
          title: messages('setting.key875'/*单据名称*/), dataIndex: 'formName', width: '10%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key854'/*单号*/),
          dataIndex: 'businessCode',
          width: '9%',
          render: value =>
            value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key876'/*事由*/), dataIndex: 'title', width: '10%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        { title: messages('setting.key877'/*币种*/), width: '5%', dataIndex: 'baseCurrency' },
        {
          title: messages('setting.key878'/*金额*/),
          width: '10%',
          dataIndex: 'totalAmount',
          sorter: true,
          render: value => value ? this.filterMoney(value) : <span className="money-cell">-</span>
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'status',
          width: props.language.code === 'zh_cn' ? '8%' : '10%',
          render: (value, record) => {
            return (
              <Badge
                text={
                  constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus') ||
                  constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
                  constants.getTextByValue(String(value), 'documentStatus')
                }
                status={
                  constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus', 'state') ||
                  constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'state') ||
                  constants.getTextByValue(String(value), 'documentStatus', 'state')
                }
              />
            )
          }
        },
        {
          title: messages('setting.key853')/*当前审批人*/,
          dataIndex: 'approvalChains',
          width: '10%',
          render: values => (
            <Popover content={values.map(value => value.approverName + ' ')}>
              {values.map(value => <span key={value.approverOID}>{value.approverName + ' '}</span>)}
            </Popover>
          ),
        }
      ],
      selectedRows: [],
      selectedRowKeys: [],
      pagination: {
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10','20','50','100']
      },
      currentApproverList: [], //当前审批人
      transferToPersonList: [], //转交给的人
      transferTxt: '', //转交意见
      visible: false, //转交处理的弹框的visible
      transferLoading: false //转交处理的laoding
    }
  }

  componentDidMount(){

  }

  /**
   *
   * @param values 控件的value值
   * @param type approver表示是当前审批人，transfer表示是转交人
   */
  handleChange = (values, type) => {
    const { currentApproverList, transferToPersonList } = this.state;
    if (type === 'approver' && this.isChange(currentApproverList, values)) {
      this.setState({currentApproverList: values}, this.getList);
    }
    if (type === 'transfer' && this.isChange(transferToPersonList, values)) {
      this.setState({transferToPersonList: values});
    }
  };

  //判断handleChange是否改变了，不知为何handleChange执行了两次，oldList，newList都最多只有一个元素
  isChange = (oldList, newList) => {
    let isChange = false;
    if (oldList.length === newList.length) {
      if (oldList.length && newList.length && newList[0].userOID !== oldList[0].userOID) {
        isChange = true;
      }
    } else {
      isChange = true;
    }
    return isChange;
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      pageSize: pagination.pageSize,
      sort
    }, () => {
      this.getList();
    });
  };

  getList = () => {
    const { currentApproverList, page, pageSize, pagination } = this.state;
    if (currentApproverList.length) {
      let params = {
        page,
        size: pageSize,
        approverOIDs: currentApproverList[0].userOID
      };
      this.setState({loading: true});
      adminApproveListService.getTransferList(params).then(res => {
        let dataSource = [];
        res.data.map(item => {
          if (item.expenseReport) {
            item.expenseReport.approvalMode = item.approvalMode;
            item.expenseReport.entityType = item.entityType;
            item.expenseReport.entityOID = item.entityOID;
            item.expenseReport.submittedDate = item.expenseReport.lastSubmittedDate;
            item.expenseReport.baseCurrencyAmount = item.expenseReport.totalAmount;
            item.expenseReport.baseCurrency = item.expenseReport.currencyCode;
            item.expenseReport.currentNodeOID = item.expenseReport.approvalChains[0].ruleApprovalNodeOID;
            item.expenseReport.version = item.expenseReport.approvalChains[0].version;
            dataSource.push(item.expenseReport || {})
          }
          if (item.application) {
            item.application.approvalMode = item.approvalMode;
            item.application.entityType = item.entityType;
            item.application.entityOID = item.entityOID;
            item.application.baseCurrencyAmount = item.application.originCurrencyTotalAmount;
            item.application.baseCurrency = item.application.originCurrencyCode;
            item.application.currentNodeOID = item.application.approvalChains[0].ruleApprovalNodeOID;
            item.application.version = item.application.approvalChains[0].version;
            dataSource.push(item.application || {})
          }
          if (item.loanBill) {
            item.loanBill.approvalMode = item.approvalMode;
            item.loanBill.entityType = item.entityType;
            item.loanBill.entityOID = item.entityOID;
            item.loanBill.employeeID = item.loanBill.applicant.employeeID;
            item.loanBill.applicantName = item.loanBill.applicant.fullName;
            // item.employeeID = item.applicant.employeeID;
            item.loanBill.totalAmount = item.loanBill.baseCurrencyAmount;
            item.loanBill.baseCurrency = item.loanBill.baseCurrencyCode;
            item.loanBill.currentNodeOID = item.loanBill.approvalChains[0].ruleApprovalNodeOID;
            item.loanBill.version = item.loanBill.approvalChains[0].version;
            dataSource.push(item.loanBill || {})
          }
        });
        pagination.total = Number(res.headers['x-total-count']) || 0;
        pagination.current = page + 1;
        this.setState({
          loading: false,
          dataSource,
          pagination
        });
      }).catch(e => {
        errorMessage(e.response);
        this.setState({loading: false});
      });
    } else {
      //没有当前审批人时清空列表
      pagination.total = 0;
      pagination.current = 1;
      this.setState({
        dataSource: [],
        page: 0,
        pagination
      });
    }
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length > 100) {
      message.warning(messages('setting.key2123')/*最多选择100条数据*/);
    } else {
      this.setState({ selectedRowKeys });
    }
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    const { selectedRows: currentSelectedRows } = this.state;
    let selectedRows = JSON.parse(JSON.stringify(currentSelectedRows));
    let item = JSON.stringify({
      approverOID: record.approverOID,
      entityOID: record.entityOID,
      entityType: record.entityType,
    });
    selected ? selectedRows.push(item) : selectedRows.delete(item);
    selectedRows.length <= 100 && this.setState({ selectedRows })
  };

  //全选
  onSelectAllRow = (selected) => {
    const { dataSource, selectedRows: currentSelectedRows } = this.state;
    let selectedRows = JSON.parse(JSON.stringify(currentSelectedRows));
    dataSource.map(item => {
      let row = JSON.stringify({
        approverOID: item.approverOID,
        entityOID: item.entityOID,
        entityType: item.entityType,
      });
      selected ? selectedRows.addIfNotExist(row) : selectedRows.delete(row);
    });
    selectedRows.length <= 100 && this.setState({ selectedRows })
  };

  //value 转交意见
  handleAdminTransfer = (value) => {
    const { currentApproverList, transferToPersonList } = this.state;
    this.setState({transferTxt: value ? value : ''});
    if (currentApproverList[0].userOID === transferToPersonList[0].userOID) {
      message.error(messages('setting.key2124')/*不能转交给自己*/);
    } else {
      this.setState({visible: true});
    }
  };

  handleClose = () => {
    this.setState({visible: false});
  };

  handleProcessTransfer = () => {
    const { currentApproverList, transferToPersonList, transferTxt, selectedRows } = this.state;
    let rows = JSON.parse(JSON.stringify(selectedRows));
    let params = {
      entities: [],
      approvalTxt: transferTxt,
      transferrePersonOID: transferToPersonList[0].userOID
    };
    rows.map(entity => {
      params.entities.push(JSON.parse(entity));
    });
    this.setState({transferLoading: true});
    adminApproveListService.setAdminTransfer(params).then(res => {
      if (res.status === 200) {
        let toastStr = messages('setting.key2125',{arg1: res.data.successNum})/*{arg1}张单据转交成功；*/;
        if (res.data.failNum) {
          toastStr += messages('setting.key2126',{arg1: res.data.failNum})/*{arg1}张单据转交失败，可能由于单据待审批状态发生变化。*/;
        } else {
          toastStr += messages('setting.key2127',{arg1: res.data.failNum})/*{arg1}张单据转交失败。*/;
        }
        message.success(toastStr);
        this.setState({transferLoading: false, visible: false});
        this.setState({
          page: 0,
          pagination: {total: 0},
          selectedRowKeys: [],
          selectedRows: []
        }, () => {
          this.getList();
        });
      }
    }).catch(e => {
      this.setState({transferLoading: false, visible: false});
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`);
    });
  };

  render() {
    const { tenantMode, company } = this.props;
    const { loading, selectedRows, selectedRowKeys, pagination, columns, dataSource, currentApproverList,
      transferToPersonList, visible, transferLoading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };
    return (
      <div className={`approve-request ${selectedRows.length ? 'bottom-100 process-monitoring-platform' : 'process-monitoring-platform'}`}>
        <Alert
          style={{marginBottom: 12}}
          message={messages('common.help')/*帮助提示*/}
          description={messages('setting.key2128')/*当员工转岗或离职等，需要批量将其待审批单据转给另外一个员工继续审批时，可以使用批量转交功能。*/}
          type="info"
          showIcon
        />
        <Row>
          <Col span={8}>
            <div style={{marginBottom: 10}}>{messages('setting.key853')/*当前审批人*/}：</div>
            <div>
              <Chooser
                type="user"
                valueKey="userOID"
                labelKey="fullName"
                value={currentApproverList}
                listExtraParams={{
                  roleType: !tenantMode ? undefined : 'TENANT',
                  status: 'all',
                  companyOID: tenantMode ? undefined : company.companyOID
                }}
                onChange={values => this.handleChange(values, 'approver')}
                single
              />
            </div>
          </Col>
          <Col span={8} offset={1}>
            <div style={{marginBottom: 10}}>{messages('setting.key2138')/*转交给*/}：</div>
            <div>
              <Chooser
                type="user"
                valueKey="userOID"
                labelKey="fullName"
                value={transferToPersonList}
                listExtraParams={{
                  roleType: !tenantMode ? undefined : 'TENANT',
                  status: 'all',
                  companyOID: tenantMode ? undefined : company.companyOID
                }}
                onChange={values => this.handleChange(values, 'transfer')}
                single
              />
            </div>
          </Col>
        </Row>
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', { total: pagination.total }/*共搜索到 {total} 条数据*/)}
            {` / ${messages('common.total.selected', { total: selectedRows.length })/*已选 {total} 条*/}`}
          </div>
        </div>
        <ResizeTable
          columns={columns}
          {...{
            rowKey: 'entityOID',
            size: 'middle',
            loading,
            rowSelection,
            pagination,
            columns,
            onChange: this.handleTableChange,
            bordered: true,
            dataSource
          }}
        />
        <Affix offsetBottom={0} className={`bottom-bar-approve ${selectedRows.length ? 'show' : 'hide'}`}>
          <ApproveBar
            admin
            buttons={['transfer']}
            batchNumber={selectedRows.length}
            adminTransferDisabled={!currentApproverList.length || !transferToPersonList.length}
            handleAdminTransfer={this.handleAdminTransfer}
          />
        </Affix>
        <Modal
          title={messages('setting.key1908')/*注意*/}
          visible={visible}
          onCancel={this.handleClose}
          closable={false}
          maskClosable={false}
          footer={[
            <Button key="close" disabled={transferLoading} onClick={this.handleClose}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="sure" type="primary" loading={transferLoading} onClick={this.handleProcessTransfer}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          {transferLoading && (
            <Row type="flex" align="middle" className="approve-all-modal">
              <Col offset={7} span={8} style={{textAlign: 'right'}}>
                <img src={checkingImg} className="img-inner" style={{right: 20}}/>
                <img src={loadingImg} className="img-out rotation"/>
              </Col>
            </Row>
          )}
          {!transferLoading && currentApproverList.length && transferToPersonList.length && (
            <div>
              <div style={{marginBottom: 10}}>
                {messages('setting.key2129',{arg1: selectedRows.length,arg2: currentApproverList[0].fullName,arg3: transferToPersonList[0].fullName})/*即将把{arg1}张单据待审批人中的{arg2}替换为{arg3}。*/}
              </div>
              <div>{messages('setting.key2130')/*替换任务执行时不可取消，是否确定？*/}</div>
            </div>
          )}
        </Modal>
      </div>
    )
  }
}

BatchTransferList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(BatchTransferList)
